/* 登录登出接口，验证码生成 */
var express = require('express');
var router = express.Router();
const db = require('../config/db');
var lang = require('../lib/lang.json');
var getCaptcha = require('../lib/captcha');
var jwt = require('jwt-simple');
var hash = require('../lib/hash');

/**
 * @apiDefine GroupUser 管理员
 */

/**
 * @apiDefine STATUS
 * @apiSuccess {string} message 文本信息
 * @apiSuccess {number} status 0：失败，1：成功
 */

router.route('/user/login')
  /**
   * @api {post} /user/login 登录
   * @apiName login
   * @apiDescription 登录接口，客户端需要支持cookie
   * @apiGroup GroupUser
   * @apiVersion 1.0.0
   * 
   * @apiParam {string} name 用户名
   * @apiParam {string} pwd 密码（明文）
   * @apiParam {string} captcha 验证码
   * @apiParam {boolean} remember 是否30天自动登录，true: 是, false: 否 
   * @apiParamExample {json} Request-Example:
   *     {
   *       "name": "LiLei",
   *       "pwd": "123456",
   *       "captcha": "12",
   *       "remember": true
   *     }
   * @apiUse STATUS
   * @apiSuccess {object} data 成功时的数据
   * @apiSuccess {string} data.name 用户名
   * @apiSuccess {string} data.token token
   * @apiSuccessExample {json} Success-Example:
   *     HTTP/1.1 200 OK
   *     {
   *       "status": 1,
   *       "message": "操作成功",
   *       "data": {
   *         "name": "LiLei",
   *         "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiYWRtaW4iLCJ0aW1lIjoxNTEyNDU2NjIzMTA1fQ.Zn3IC15MxoABaMZcy0nfqubzYEg-wky5IiwKFCvRuwU"
   *       }
   *     }
   */
  .post (function (req, res) {
    try {
      var name = req.body.name;
      var pwd = req.body.pwd;
      var captcha = req.body.captcha;
      var remember = req.body.remember;
      if (captcha === '' || captcha != req.session.captcha) {
        req.session.captcha = '';
        return res.status(200).json({
          status: 0,
          message: `${lang.error},验证码错误`
        })
      }

      var uInfo = db.get('user').find({ name: name }).value();
      pwd = hash.communism(pwd, uInfo.salt);

      if (uInfo) {
        if (name === uInfo.name && pwd === uInfo.pwd) {
          req.session.captcha = '';
          var token = jwt.encode(
            {
              name: name,
              time: new Date().getTime()
            },
            lang.jwtSecret
          );
         
          if (remember) {
            var dateNow = new Date();
            var day = dateNow.getDate();
            var date = dateNow.setDate(day + 30);
            db.get('user').find({name: name}).assign({
              remember: date
            }).write();
          } else {
            db.get('user').find({ name: name }).assign({
              remember: 0
            }).write();
          }
          return res.status(200).json({
            status: 1,
            message: lang.success,
            data: {
              name: name,
              token: token
            }
          })
        } else {
          req.session.captcha = '';
          return res.status(200).json({
            status: 0,
            message: `${lang.error},用户名或密码错误`
          })
        }
      } else {
        req.session.captcha = '';
        return res.status(200).json({
          status: 0,
          message: `${lang.error},用户名不存在`
        })
      }
    } catch(e) {
      console.error(e);
    }
  });

router.route('/user/autoLogin')
  /**
   * @api {post} /user/autoLogin 自动登录
   * @apiName autoLogin
   * @apiDescription 自动登录接口，客户端需要支持cookie
   * @apiGroup GroupUser
   * @apiVersion 1.0.0
   * 
   * @apiParam {string} name 用户名
   * @apiParam {string} token token令牌
   * @apiParamExample {json} Request-Example:
   *     {
   *       "name": "LiLei",
   *       "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiYWRtaW4iLCJ0aW1lIjoxNTEyNDU2NjIzMTA1fQ.Zn3IC15MxoABaMZcy0nfqubzYEg-wky5IiwKFCvRuwU"
   *     }
   * @apiUse STATUS
   * @apiSuccess {object} data 成功时的数据
   * @apiSuccess {string} data.name 用户名
   * @apiSuccess {string} data.token token令牌
   * @apiSuccessExample {json} Success-Example:
   *     HTTP/1.1 200 OK
   *     {
   *       "status": 1,
   *       "message": "操作成功",
   *       "data": {
   *         "name": "LiLei",  
   *         "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiYWRtaW4iLCJ0aW1lIjoxNTEyNDU2NjIzMTA1fQ.Zn3IC15MxoABaMZcy0nfqubzYEg-wky5IiwKFCvRuwU"
   *       }
   *     }
   */
  .post (function (req, res, next) {
    try {
      var uname = req.body.name;
      var token = req.body.token;
      if (token) {
        var loginInfo = jwt.decode(token, lang.jwtSecret);
      } else {
        return res.status(200).json({
          status: 0,
          message: '请手动登录'
        })
      }

      var autoDate = db.get('user').find({ name: loginInfo.name }).value().remember;
      if (uname === loginInfo.name && new Date().getTime() < autoDate) {
        req.session.captcha = '';
        var newToken = jwt.encode(
          {
            name: loginInfo.name,
            time: new Date().getTime()
          },
          lang.jwtSecret
        );
        return res.status(200).json({
          status: 1,
          message: lang.success,
          data: {
            name: loginInfo.name,
            token: newToken
          }
        })
      } else {
        return res.status(200).json({
          status: 0,
          message: '请手动登录'
        })
      }
    } catch (e) {
      console.error(e);
    }
  });

router.route('/captcha')
  /**
   * @api {get} /user/captcha 获取验证码
   * @apiName getCaptcha
   * @apiDescription 获取验证码接口，客户端需要支持cookie
   * @apiGroup GroupUser
   * @apiVersion 1.0.0
   * 
   * @apiUse STATUS
   * @apiSuccess {string} data svg字符串
   * @apiSuccessExample {json} Success-Example:
   *     HTTP/1.1 200 OK
   *     {
   *       "status": 1,
   *       "message": "操作成功",
   *       "data": "<svg>...</svg>"
   *     }
   */
  .get (function (req, res) {
    try {
      var captchaCode = getCaptcha.getCaptcha();
      req.session.captcha = captchaCode.text;
      
      res.type('svg');
      return res.status(200).json({
        status: 1,
        message: lang.success,
        data: captchaCode.data,
      });
    } catch(e) {
      console.error(e);
    }
});

router.route('/user/logout')
  /**
   * @api {get} /user/logout 退出登录
   * @apiName logout
   * @apiDescription 退出登录接口，请求成功后清空登录session和cookie信息
   * @apiGroup GroupUser
   * @apiVersion 1.0.0
   * 
   * @apiParam {string} name 用户名
   * 
   * @apiUse STATUS
   * @apiSuccessExample {json} Success-Example:
   *     HTTP/1.1 200 OK
   *     {
   *       "status": 1,
   *       "message": "操作成功",
   *     }
   */
  .get(function (req, res) {
    try {
      var name = req.query.name;
      req.session.captcha = '';
      res.clearCookie('login');
      db.get('user').find({ name: name }).assign({
        remember: 0
      }).write();
      return res.status(200).json({
        status: 1,
        message: lang.success,
      });
    } catch (e) {
      console.error(e);
    }
  });

module.exports = router;